package com.jogger.newprint.ui;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.jogger.newprint.R;
import com.jogger.newprint.adapter.MyBlueToothAdapter;
import com.jogger.newprint.base.BaseActivity;
import com.jogger.newprint.bean.BlueTooth;
import com.jogger.newprint.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import timber.log.Timber;

public class ConnectActivity extends BaseActivity implements SwitchCompat.OnCheckedChangeListener, MyBlueToothAdapter.OnItemClickListener {
    @BindView(R.id.rv_content)
    RecyclerView rv_content;
    @BindView(R.id.my_switch)
    SwitchCompat my_switch;
    ProgressDialog mProgressDialog;
    private BluetoothDevice device;
    private List<BlueTooth> mBlueTooths;
    private MyBlueToothAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_connect;
    }

    @Override
    protected void init() {
        super.init();
        my_switch.setOnCheckedChangeListener(this);
        mProgressDialog = new ProgressDialog(this);
        mBlueTooths = new ArrayList<>();
        mAdapter = new MyBlueToothAdapter(this);
        rv_content.setLayoutManager(new LinearLayoutManager(this));
        rv_content.setAdapter(mAdapter);
        mAdapter.loadData(mBlueTooths);
        mAdapter.setOnItemClickListener(this);
        mProgressDialog.setMessage("扫描中");
    }

    @Override
    protected void loadData() {
        super.loadData();
        //创建一个IntentFilter对象，将其action指定为BluetoothDevice.ACTION_FOUND,查找蓝牙
        IntentFilter intentFileter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //注册广播接收器
        registerReceiver(mReceiver, intentFileter);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        openBluetooth();
    }

    private void openBluetooth() {
        //bluetoothAdapter.enable();
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(intent);
            }
        } else {
            Toast.makeText(this, "没有蓝牙设备", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mProgressDialog.show();
            mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mBluetoothAdapter != null) {
                        //停止扫描
                        mBluetoothAdapter.cancelDiscovery();
                    }
                }
            });
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothAdapter.startDiscovery();
            ToastUtil.showToast(ConnectActivity.this, "开始扫描");
        } else {
            mBlueTooths.clear();
            mAdapter.notifyDataSetChanged();
        }
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Timber.e("---------------------onReceive");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //得到intent里面的信息
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device == null) return;
                String deviceName = device.getName();
                if (deviceName == null) return;
                //排除机型
//                if (!device.getName().toLowerCase().startsWith("pt-")) return;
//                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
//                PairedMaclist.add(device.getAddress());
                BlueTooth bean = new BlueTooth();
                bean.setmAdress(device.getAddress());
                bean.setmName(device.getName());
                if (!mBlueTooths.contains(bean)) {
                    mBlueTooths.add(bean);
                    mAdapter.notifyDataSetChanged();
                    //Toast.makeText(ConnectionActivity.this, "发现蓝牙设备", Toast.LENGTH_SHORT).show();
                }
            } else if (intent.getAction().equals(
                    "android.bluetooth.device.action.PAIRING_REQUEST")) {
                /*
                try
                {
                    ClsUtils.setPin(device.getClass(), device, "1234"); // 手机和蓝牙采集器配对
                    ClsUtils.createBond(device.getClass(), device);
                    ClsUtils.cancelPairingUserInput(device.getClass(), device);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                */
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onItemClick(View v, BlueTooth blueTooth) {
        //判断打印机是否已经连接 如果已经连接 提示是否断开连接
        //选择打印机
        Intent intent=new Intent();
        intent.putExtra("printName", blueTooth.getmName());
        intent.putExtra("printMacAddress", blueTooth.getmAdress());
        setResult(RESULT_OK,intent);
        //Toast.makeText(ConnectionActivity.this, "已连接打印机:" + CurrentLabel.lb.printerInfo.pritnerName, Toast.LENGTH_SHORT).show();
        finish();
    }
}
